package com.dragon.utilslibrary.tools;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;


import com.dragon.utilslibrary.AppConfig;

import java.io.IOException;

/**
 * 调用系统铃声
 */

public class RingUtil {

    private MediaPlayer mMediaPlayer;
    private static RingUtil instance;
    private RingUtil(){
        mMediaPlayer = getMediaPlayer(AppConfig.mContext);
    }
    public static RingUtil getInstance(){
        if(instance == null){
            instance = new RingUtil();
        }
        return instance;
    }
    public void startAlarm() {
        try {
            if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
                mMediaPlayer.start();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     *
     * @param delayStop 多久后停止，单位毫秒
     */
    public void startAlarm(long delayStop) {
        if(mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            startAlarm();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    stopAlarm();
                }
            }, delayStop);
        }
    }
    public void stopAlarm(){
        try {
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer = getMediaPlayer(AppConfig.mContext);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    private MediaPlayer getMediaPlayer(Context context){
        try {
            mMediaPlayer = MediaPlayer.create(context, getSystemDefultRingtoneUri(context));
            mMediaPlayer.setLooping(true);

            mMediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return mMediaPlayer;
    }

    //获取系统默认铃声的Uri
    private Uri getSystemDefultRingtoneUri(Context context) {
        return RingtoneManager.getActualDefaultRingtoneUri(context,
                RingtoneManager.TYPE_RINGTONE);
    }
}
